package com.ztom.v2;

import java.util.List;

/**
 * @author ZhangTao
 */
public class Code86WordBreak {

    public boolean wordBreak(String s, List<String> wordDict) {
//        return process(s, wordDict, 0);
        boolean[] dp = new boolean[s.length() + 1];
        dp[s.length()] = true;
        for (int i = s.length() - 1; i >= 0; i--) {
            for (int j = i + 1; j <= s.length(); j++) {
                if (wordDict.contains(s.substring(i, j)) && dp[j]) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[0];
    }

    public boolean process(String s, List<String> wordDict, int index) {
        if (index == s.length()) {
            // 字符串全部成功切割
            return true;
        }
        for (int i = index + 1; i <= s.length(); i++) {
            if (wordDict.contains(s.substring(index, i))
                    // 左部分已匹配, 继续去右部分匹配
                    && process(s, wordDict, i)) {
                return true;
            }
        }
        return false;
    }
}
